/**
 *    Copyright 2009-2020 the original author or authors.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package org.apache.ibatis.builder.xml;

import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.builder.BaseBuilder;
import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.loader.ProxyFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaClass;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.AutoMappingUnknownColumnBehavior;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.LocalCacheScope;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.type.JdbcType;

/**
 * @author Clinton Begin
 * @author Kazuki Shimizu
 */
/*xxx: 具体建造者，它主要负责解析  mybatis-config.xml 配置文件*/
public class XMLConfigBuilder extends BaseBuilder {

  /*xxx: 标识 是否已经解析过  mybatis-config.xml配置文件*/
  private boolean parsed;
  /*xxx: 用于解析 mybatis-config.xml 配置文件的  XPathParser对象*/
  private final XPathParser parser;
  /*xxx: 标识 <environment> 配置的名称，默认读取 <environment> 标签的 default 属性*/
  private String environment;
  /*xxx: 负责 创建和缓存  Reflector 对象*/
  private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();

  public XMLConfigBuilder(Reader reader) {
    this(reader, null, null);
  }

  public XMLConfigBuilder(Reader reader, String environment) {
    this(reader, environment, null);
  }

  public XMLConfigBuilder(Reader reader, String environment, Properties props) {
    this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
  }

  public XMLConfigBuilder(InputStream inputStream) {
    this(inputStream, null, null);
  }

  public XMLConfigBuilder(InputStream inputStream, String environment) {
    this(inputStream, environment, null);
  }

  public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
    this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
  }

  private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
    super(new Configuration());
    ErrorContext.instance().resource("SQL Mapper Configuration");
    this.configuration.setVariables(props);
    this.parsed = false;
    this.environment = environment;
    this.parser = parser;
  }

  /*xxx: 解析  mybatis-config.xml 配置文件的入口*/
  public Configuration parse() {
    /*xxx: 探测是否已经解析过配置文件*/
    if (parsed) {
      throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
    /*xxx: 在 mybatis-config.xml 配置文件中，查找  <configuration> 节点，并开始解析*/
    /*xxx: 以 confgiration为根节点进行解析 */
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
  }

  private void parseConfiguration(XNode root) {
    try {
      // issue #117 read properties first
      /*xxx: 解析 <properties> 节点 */
      propertiesElement(root.evalNode("properties"));
      /*xxx: 解析 <settings> 节点*/
      Properties settings = settingsAsProperties(root.evalNode("settings"));
      /*xxx: 设置  vfsImpl 字段*/
      loadCustomVfs(settings);
      loadCustomLogImpl(settings);
      /*xxx: 解析  <typeAliases> 节点*/
      typeAliasesElement(root.evalNode("typeAliases"));
      /*xxx: 解析 <plugins> 节点*/
      pluginElement(root.evalNode("plugins"));
      /*xxx: 解析 <objectFactory>节点*/
      objectFactoryElement(root.evalNode("objectFactory"));
      /*xxx: 解析 <objectWrapperFactory>节点*/
      objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
      /*xxx: 解析 <reflectorFactory>节点*/
      reflectorFactoryElement(root.evalNode("reflectorFactory"));
      /*xxx: 将 settings 值，设置到 Configuration中*/
      settingsElement(settings);
      // read it after objectFactory and objectWrapperFactory issue #631
      /*xxx: 设置 <environments> 节点*/
      environmentsElement(root.evalNode("environments"));
      /*xxx: 解析  <databaseIdProvider> 节点*/
      databaseIdProviderElement(root.evalNode("databaseIdProvider"));
      /*xxx: 解析 <typeHandlers> 节点*/
      typeHandlerElement(root.evalNode("typeHandlers"));
      /*xxx: 解析  <mappers> 节点*/
      mapperElement(root.evalNode("mappers"));
    } catch (Exception e) {
      throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
    }
  }

  private Properties settingsAsProperties(XNode context) {
    if (context == null) {
      return new Properties();
    }
    /*xxx: 解析 <settings> 的子节点 的 name 和 value属性，并返回 Properties对象*/
    Properties props = context.getChildrenAsProperties();
    // Check that all settings are known to the configuration class
    /*xxx: 创建 Configuration对应的 MetaClass对象*/
    MetaClass metaConfig = MetaClass.forClass(Configuration.class, localReflectorFactory);
    /*xxx: 检测 Configuration中是否定义了 key 之地那个属性的相应setter方法*/
    for (Object key : props.keySet()) {
      if (!metaConfig.hasSetter(String.valueOf(key))) {
        throw new BuilderException("The setting " + key + " is not known.  Make sure you spelled it correctly (case sensitive).");
      }
    }
    return props;
  }

  private void loadCustomVfs(Properties props) throws ClassNotFoundException {
    String value = props.getProperty("vfsImpl");
    if (value != null) {
      String[] clazzes = value.split(",");
      for (String clazz : clazzes) {
        if (!clazz.isEmpty()) {
          @SuppressWarnings("unchecked")
          Class<? extends VFS> vfsImpl = (Class<? extends VFS>)Resources.classForName(clazz);
          configuration.setVfsImpl(vfsImpl);
        }
      }
    }
  }

  private void loadCustomLogImpl(Properties props) {
    Class<? extends Log> logImpl = resolveClass(props.getProperty("logImpl"));
    configuration.setLogImpl(logImpl);
  }

  private void typeAliasesElement(XNode parent) {
    if (parent != null) {
      /*xxx: 处理全部子节点*/
      for (XNode child : parent.getChildren()) {
        /*xxx: 处理 <package> 节点*/
        if ("package".equals(child.getName())) {
          /*xxx: 获取指定的包名*/
          String typeAliasPackage = child.getStringAttribute("name");
          /*xxx: 通过 TypeAliasRegistry 扫描指定包中的所有的类，并 解析  @Alias注解，完成别名注册*/
          configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
          /*xxx: 处理 <typeAlias> 节点*/
        } else {
          /*xxx: 获取指定的别名*/
          String alias = child.getStringAttribute("alias");
          /*xxx: 获取别名对应的类型*/
          String type = child.getStringAttribute("type");
          try {
            Class<?> clazz = Resources.classForName(type);
            if (alias == null) {
              /*xxx: 扫描 @Alias注解，完成注册*/
              typeAliasRegistry.registerAlias(clazz);
            } else {
              /*xxx: 注册别名*/
              typeAliasRegistry.registerAlias(alias, clazz);
            }
          } catch (ClassNotFoundException e) {
            throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
          }
        }
      }
    }
  }

  private void pluginElement(XNode parent) throws Exception {
    if (parent != null) {
      /*xxx: 遍历全部子节点 即 <plugin> 节点*/
      for (XNode child : parent.getChildren()) {
        /*xxx: 获取 <plugin> 节点的  interceptor属性的值*/
        String interceptor = child.getStringAttribute("interceptor");
        /*xxx: 获取  <plugin> 节点下  <properties> 配置的信息，并形成  Properties 对象*/
        Properties properties = child.getChildrenAsProperties();
        /*xxx: 通过  TypeAliasRegistry 解析别名之后，实例化  Interceptor 对象 */
        Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).getDeclaredConstructor().newInstance();
        /*xxx: 设置 Interceptor的属性*/
        interceptorInstance.setProperties(properties);
        /*xxx: 记录  Interceptor 对象 */
        configuration.addInterceptor(interceptorInstance);
      }
    }
  }

  private void objectFactoryElement(XNode context) throws Exception {
    if (context != null) {
      /*xxx: 获取 <objectFactory> 节点的 type 属性 */
      String type = context.getStringAttribute("type");
      /*xxx: 获取 <objectFactory> 节点下配置的信息,并形成 Properties对象*/
      Properties properties = context.getChildrenAsProperties();
      /*xxx: 进行别名解析后，实例化自定义 ObjectFactory实现*/
      ObjectFactory factory = (ObjectFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      /*xxx: 设置自定义 ObjectFactory 的属性，完成初始化的相关操作*/
      factory.setProperties(properties);
      /*xxx: 将自定义 ObjectFactory对象，记录到Configuration对象的 objectFactory字段中*/
      configuration.setObjectFactory(factory);
    }
  }

  private void objectWrapperFactoryElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      ObjectWrapperFactory factory = (ObjectWrapperFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      configuration.setObjectWrapperFactory(factory);
    }
  }

  private void reflectorFactoryElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      ReflectorFactory factory = (ReflectorFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      configuration.setReflectorFactory(factory);
    }
  }

  private void propertiesElement(XNode context) throws Exception {
    if (context != null) {
      /*xxx: 解析 <properties> 的子节点(<property>标签)的 name  和  value 属性，并记录到 Properties中*/
      Properties defaults = context.getChildrenAsProperties();
      /*xxx: 解析 <properties> 的 resource 和 url 属性，这两个属性，用于确定 properties配置文件的位置*/
      String resource = context.getStringAttribute("resource");
      String url = context.getStringAttribute("url");
      /*xxx: resource 和  url 属性不能同时存在，否则抛异常*/
      if (resource != null && url != null) {
        throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
      }
      /*xxx: 加载 resource 属性 或 url 属性指定的  properties文件*/
      if (resource != null) {
        defaults.putAll(Resources.getResourceAsProperties(resource));
      } else if (url != null) {
        defaults.putAll(Resources.getUrlAsProperties(url));
      }
      Properties vars = configuration.getVariables();
      /*xxx: 与 Configuration对象中的  variables集合合并*/
      if (vars != null) {
        defaults.putAll(vars);
      }
      /*xxx: 更新 XPathParser 和  Configuration的variables字段*/
      parser.setVariables(defaults);
      configuration.setVariables(defaults);
    }
  }

  private void settingsElement(Properties props) {
    /*xxx: 是否开启自动映射的功能,默认 PARTIAL,将自动映射 没有嵌套定义映射的结果集 */
    configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
    /*xxx: 自动映射未知列的行为，默认不映射*/
    configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
    /*xxx: 设置是否启用缓存，默认启用*/
    configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
    /*xxx: 设置代理工厂实例， 该代理工厂为必设的属性，这里进行了强转，否则会报错*/
    configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
    /*xxx: 设置是否允许懒加载，默认 关闭*/
    configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));
    /*xxx: 设置 是否允许 侵入性懒加载，默认关闭*/
    configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false));
    /*xxx: 设置是否允许多结果集， 默认允许*/
    configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));
    /*xxx: 设置是否 使用 列标签，默认允许*/
    configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));
    /*xxx: 设置自动生成主键,默认关闭*/
    configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));
    /*xxx: 设置默认的 线程池类型，默认SIMPLE*/
    configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));
    /*xxx: 设置默认的 statement超时时间，默认不超时*/
    configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));
    /*xxx: 设置默认的 拉取大小，默认没限制*/
    configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));
    /*xxx: 设置默认的 结果集 类型*/
    configuration.setDefaultResultSetType(resolveResultSetType(props.getProperty("defaultResultSetType")));
    /*xxx: 设置大小写转 驼峰命名，默认 关闭*/
    configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));
    /*xxx: 设置 safeRowBoundsEnabled，默认关闭*/
    configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));
    /*xxx: 设置 本地缓存域级别，默认SESSION*/
    configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));
    /*xxx: 设置为空的jdbc类型*/
    configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));
    /*xxx: 设置 懒加载触发器方法， 默认 equals,clone,hashCode,toString 会触发*/
    configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
    /*xxx: 设置 safeResultHandlerEnabled，默认开启*/
    configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
    /*xxx: 设置 默认的 脚本语言*/
    configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
    /*xxx: 设置默认的枚举类型处理器*/
    configuration.setDefaultEnumTypeHandler(resolveClass(props.getProperty("defaultEnumTypeHandler")));
    /*xxx: 设置 是否允许调用 属性为null，的setter方法*/
    configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
    /*xxx: 设置是否使用实际的参数名作为索引名，默认为 真*/
    configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));
    /*xxx: 设置 sql查询为空时，是否返回空实例，默认关闭*/
    configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));
    /*xxx: 设置日志的前缀 */
    configuration.setLogPrefix(props.getProperty("logPrefix"));
    /*xxx: 设置 配置工厂*/
    configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
    /*xxx: 设置 在sql中收缩空格，默认关闭*/
    configuration.setShrinkWhitespacesInSql(booleanValueOf(props.getProperty("shrinkWhitespacesInSql"), false));
    /*xxx: 设置默认的 sql类型提供器*/
    configuration.setDefaultSqlProviderType(resolveClass(props.getProperty("defaultSqlProviderType")));
  }

  private void environmentsElement(XNode context) throws Exception {
    if (context != null) {
      /*xxx: 未指定 XMLConfigBuilder.environment字段，则使用 default 属性指定的 <environment> */
      if (environment == null) {
        environment = context.getStringAttribute("default");
      }
      /*xxx: 遍历 子节点 (即 <environment> 节点)*/
      for (XNode child : context.getChildren()) {
        String id = child.getStringAttribute("id");
        /*xxx: 是否时当前指定的 environment*/
        if (isSpecifiedEnvironment(id)) {
          /*xxx: 创建 TransactionFactory，通过 TypeAliasRegistry解析别名后，实例化TransactionFactory*/
          TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
          /*xxx: 创建 DataSoruceFactory和 DataSource*/
          DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
          DataSource dataSource = dsFactory.getDataSource();
          /*xxx: 创建  Environment , Environment 中封装了 上面创建的  TransactionFactory对象以及 DataSource的对象*/
          Environment.Builder environmentBuilder = new Environment.Builder(id)
              .transactionFactory(txFactory)
              .dataSource(dataSource);
          /*xxx: 将 Environment对象记录到Configuration.environment 字段中*/
          configuration.setEnvironment(environmentBuilder.build());
        }
      }
    }
  }

  /*xxx: 解析  <databaseIdProvider>节点*/
  private void databaseIdProviderElement(XNode context) throws Exception {
    /*xxx: hibernate 可以直接帮助开发人员 屏蔽多种数据库产品在SQL语言支持方面的差异*/
    /*xxx: 通过在  mybatis-config.xml 配置文件中的 <databaseIdProvider> 定义所有支持的数据库产品的databaseId，
    *     在映射配置文件中 定义 SQL语句时，通过 databaseId指定该 SQL语句应用的语句，也可以实现类似功能*/
    DatabaseIdProvider databaseIdProvider = null;
    if (context != null) {
      String type = context.getStringAttribute("type");
      // awful patch to keep backward compatibility
      /*xxx: 为了保证兼容性，修改 type取值*/
      if ("VENDOR".equals(type)) {
        type = "DB_VENDOR";
      }
      /*xxx： 解析相关配置信息*/
      Properties properties = context.getChildrenAsProperties();
      /*xxx: 创建 DatabaseIdProvider对象*/
      databaseIdProvider = (DatabaseIdProvider) resolveClass(type).getDeclaredConstructor().newInstance();
      /*xxx: 配置 DatabaseIdProvider，完成初始化*/
      databaseIdProvider.setProperties(properties);
    }
    Environment environment = configuration.getEnvironment();
    if (environment != null && databaseIdProvider != null) {
      /*xxx: 通过前面确定的 DataSource 获取 databaseId,并记录到  Configuration.databaseId字段中*/
      String databaseId = databaseIdProvider.getDatabaseId(environment.getDataSource());
      configuration.setDatabaseId(databaseId);
    }
  }

  private TransactionFactory transactionManagerElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties props = context.getChildrenAsProperties();
      TransactionFactory factory = (TransactionFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      factory.setProperties(props);
      return factory;
    }
    throw new BuilderException("Environment declaration requires a TransactionFactory.");
  }

  private DataSourceFactory dataSourceElement(XNode context) throws Exception {
    if (context != null) {
      String type = context.getStringAttribute("type");
      Properties props = context.getChildrenAsProperties();
      DataSourceFactory factory = (DataSourceFactory) resolveClass(type).getDeclaredConstructor().newInstance();
      factory.setProperties(props);
      return factory;
    }
    throw new BuilderException("Environment declaration requires a DataSourceFactory.");
  }

  private void typeHandlerElement(XNode parent) {
    if (parent != null) {
        /*xxx: 遍历处理所有的节点*/
      for (XNode child : parent.getChildren()) {
        /*xxx: 处理 <package> 节点*/
        if ("package".equals(child.getName())) {
          /*xxx: 获取该节点的 name 属性*/
          String typeHandlerPackage = child.getStringAttribute("name");
          /*xxx: 将其注册到 注册中心*/
          typeHandlerRegistry.register(typeHandlerPackage);
          /*xxx: 处理 <typeHandler>节点*/
        } else {
          /*xxx: 获取 java类型*/
          String javaTypeName = child.getStringAttribute("javaType");
          /*xxx: 获取 jdbc类型*/
          String jdbcTypeName = child.getStringAttribute("jdbcType");
          /*xxx: 设置类型转换器*/
          String handlerTypeName = child.getStringAttribute("handler");
          Class<?> javaTypeClass = resolveClass(javaTypeName);
          /*xxx: 枚举转换*/
          JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
          Class<?> typeHandlerClass = resolveClass(handlerTypeName);
          if (javaTypeClass != null) {
            if (jdbcType == null) {
              typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
            } else {
              typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
            }
          } else {
            typeHandlerRegistry.register(typeHandlerClass);
          }
        }
      }
    }
  }

  private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
      /*xxx: 处理 <mappers> 的子节点*/
      for (XNode child : parent.getChildren()) {
        /*xxx: <package>子节点*/
        if ("package".equals(child.getName())) {
          String mapperPackage = child.getStringAttribute("name");
          /*xxx:扫描指定的包，并向 MapperRegistry注册 Mapper接口，它根据包名注册*/
          configuration.addMappers(mapperPackage);
        } else {
          /*xxx: 获取  <mapper>节点的  resource,url,class属性，这三个属性互斥*/
          String resource = child.getStringAttribute("resource");
          String url = child.getStringAttribute("url");
          String mapperClass = child.getStringAttribute("class");
          /*xxx: 如果<mapper> 节点指定的是 resource属性*/
          if (resource != null && url == null && mapperClass == null) {
            ErrorContext.instance().resource(resource);
            InputStream inputStream = Resources.getResourceAsStream(resource);
            /*xxx: 则 创建 XMLMapperBuilder对象*/
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
            mapperParser.parse();
            /*xxx: 如果 <mapper> 节点 指定的 是 url属性*/
          } else if (resource == null && url != null && mapperClass == null) {
            ErrorContext.instance().resource(url);
            InputStream inputStream = Resources.getUrlAsStream(url);
            /*xxx: 则 也是创建 XMLMapperBuilder对象*/
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
            mapperParser.parse();
            /*xxx: 如果 <mapper> 节点 指定的 是 class属性*/
          } else if (resource == null && url == null && mapperClass != null) {
            Class<?> mapperInterface = Resources.classForName(mapperClass);
            /*xxx: 则向 MapperRegistry注册该Mapper接口*/
            configuration.addMapper(mapperInterface);
          } else {
            throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
          }
        }
      }
    }
  }

  private boolean isSpecifiedEnvironment(String id) {
    if (environment == null) {
      throw new BuilderException("No environment specified.");
    } else if (id == null) {
      throw new BuilderException("Environment requires an id attribute.");
    } else if (environment.equals(id)) {
      return true;
    }
    return false;
  }

}
